package org.watchrecords.managers;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import org.watchrecords.dbo.Incident;
import org.watchrecords.dbo.Offender;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.wideplay.warp.persist.Transactional;
import com.wideplay.warp.persist.dao.Finder;

public class IncidentManager {
    private Provider<EntityManager> emProvider;
    private OffenderManager offenderManager;
    
    protected IncidentManager() {}

    @Inject
    public IncidentManager(Provider<EntityManager> emProvider, OffenderManager offenderManager) {
        this.emProvider = emProvider;
        this.offenderManager = offenderManager;
    }
    
    public Incident getIncident(int id) {
        return emProvider.get().find(Incident.class, id);
    }
    
    @Transactional
    public void saveIncident(Incident incident) {
        if (incident.getId() == null) {
            incident.setCreated(new Date());
        }
        
        List<Offender> offenders = new ArrayList<Offender>(incident.getOffenders());
        incident.getOffenders().clear();
        
        for (Offender offender: offenders) {
            incident.getOffenders().add(offenderManager.getOffender(offender.getId()));
        }
        
        EntityManager em = emProvider.get();
        em.persist(incident);
    }
    
    @Transactional
    public void deleteIncident(Incident incident) {
        emProvider.get().remove(emProvider.get().merge(incident));
    }
    
    @Finder(namedQuery = "getIncidents")
    public List<Incident> getIncidents() {
        throw new AssertionError();
    }
}
